import  methods
import json5, json
import tool
import pandas as pd

# 板块名称
bankuai_name = '摘帽'

cookies_str = methods.get_xueqiu_cookies()
print(f'雪球网cookie: {cookies_str}')
filter_list = []

stocks_list = json5.load(open("./tonghuashun_chengfen.json", "r", encoding='utf8'))
print(f'{bankuai_name}板块成分股数量', len(stocks_list))

stocks_list2 = list(map(tool.add_symbol, stocks_list))

# print(stocks_list2)

for index, stock in enumerate(stocks_list2):
  try:
    # pb pe 等基本指标
    stock_info = methods.get_info(stock['symbol'], cookies_str)
    one_stock = [
      stock_info['symbol'],
      stock_info['name'],
      stock_info['market_capital'],
      stock_info['current'],
      stock_info['pb'],
      stock_info['pe_forecast'],
      stock_info['dividend_yield'],         # 分红
      stock_info['glzfl'],                  # 股利支付率
      stock_info['roe'],
      stock_info['roe_pe'],
      stock_info['lowIndicator']
    ]

    print(f"[{index + 1}] {one_stock}")
    filter_list.append(one_stock)

  except Exception as e:
    print(f"处理股票 {stock.get('symbol', '未知')} 时出错: {str(e)}")
    print(f"cookies可能过期，请访问 https://xueqiu.com/S/SH600519 手动获取")
    # 跳过当前股票，继续下一次循环
    continue

# 依据ROE/PE排序
filter_list.sort(key = lambda x: x[9], reverse=True)
print('循环完成', len(filter_list))

result = pd.DataFrame(filter_list, columns=['股票代码', '股票名称', '总市值/亿', '当前股价', '市净率', '市盈率(动)', '股息率%', '股利支付率%', 'ROE',  'ROE/PE', '低位指数'])
result.to_excel(f"./selected/{tool.hashtoday()}-{bankuai_name}.xlsx", index=False)